import { BLOCK_COLLECT_SPEED, BLOCK_COLLECT_ZINDEX, NODE_POOL_NAME } from "../Common/Constant";
import NodePool from "../Libraries/NodePool";
import CatcherController from "./CatcherController";
import GamePlayController from "./GamePlayController";
import SingleBlockController from "./SingleBlockController";
import TopAreaTs from "./TopAreaTs";
import catchMoneyFly from "./catchMoneyFly";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SingleCatcherController extends cc.Component {

    private _currentBlock: SingleBlockController = null;
    private _catchingTween: cc.Tween = null;
   
    /**
     * 接收一个方块
     * @param block 被接收的方块
     */
    public catchBlock(block: SingleBlockController): void {
        // if (block.isEliminating) return;
        this._currentBlock = block;
        block.stayCatcher = this;
        block.isMoving = true;
        if (this._catchingTween) this._catchingTween.stop();
        const layerMap = GamePlayController.I.nodeLayerMap;
        let mapPosFrom: cc.Vec2 = layerMap.convertToNodeSpaceAR(block.node.convertToWorldSpaceAR(cc.v2(0, 0)));
        let mapPosTo: cc.Vec2 = layerMap.convertToNodeSpaceAR(this.node.convertToWorldSpaceAR(cc.v2(0, 0)));
        let distance: number = mapPosFrom.sub(mapPosTo).mag();
        block.node.setParent(layerMap);
        block.node.setPosition(mapPosFrom);
        block.node.zIndex = BLOCK_COLLECT_ZINDEX + CatcherController.I.catchers.indexOf(this);
        this._catchingTween = cc.tween(block.node)
            .to(
                distance / BLOCK_COLLECT_SPEED
                , { x: mapPosTo.x, y: mapPosTo.y }
                , { easing: cc.easing.quadOut }
            )
            .call(() => {
                this.__onCatched();
                this._currentBlock.onCatched();
            })
            .start();
    }

    /**
     * 清空方块引用
     */
    public discardBlock(): void {
        this._currentBlock = null;
        if (this._catchingTween) {
            this._catchingTween.stop();
            this._catchingTween = null;
        }
    }

    /**
     * 消除当前块之后恢复为空的接收单位
     */
    public afterEliminate(): void {
        this._currentBlock = null;
        if (this._catchingTween) {
            this._catchingTween.stop();
            this._catchingTween = null;
        }
    }

    /**
     * 清除干净
     */
    public clean(): void {
        if (!this._currentBlock) return;
        NodePool.putItem(NODE_POOL_NAME.singleBlock, this._currentBlock.node);
        this._currentBlock = null;
    }

    /**
     * 获取当前块
     */
    public getCurrentBlock(): SingleBlockController {
        return this._currentBlock;
    }

    /**
     * 接收到一个方块之后执行
     * @param checkEliminate 是否检测消除
     */
    private __onCatched(): void {
        this._catchingTween = null;
    }
    //飞翔的钱
    flyMoney(index){
        let worldPos = this.node.parent.convertToWorldSpaceAR(this.node.position)
        catchMoneyFly.I.flyMoney(worldPos,index)
    }
}
